package com.pig4cloud.pig.common.core.util;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {
	public static <T extends TreeNode> List<T> buildTree(List<T> list, Long rootId) {
		List<T> tree = new ArrayList<>();
		for (T node : list) {
			if (rootId.equals(node.getParentId())) {
				tree.add(findChildren(node, list));
			}
		}
		return tree;
	}

	private static <T extends TreeNode> T findChildren(T node, List<T> list) {
		for (T child : list) {
			if (node.getId().equals(child.getParentId())) {
				if (node.getChildren() == null) {
					node.setChildren(new ArrayList<T>());
				}
				((List<T>) node.getChildren()).add(findChildren(child, list));
			}
		}
		return node;
	}
}
